import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);
// 统一引入需要显示的组件
const Login = () => import("../views/Login.vue");
const Layout = () => import("../views/Layout.vue");
const Index = () => import("../views/Index.vue");
const Menu = () => import("../views/Menu/Index.vue");
const Role = () => import("../views/Role/Index.vue");
const User = () => import("../views/User/Index.vue");
const Category = () => import("../views/Category/Index.vue");
const Specs = () => import("../views/Specs/Index.vue");
const Goods = () => import("../views/Goods/Index.vue");

// 路由表 表明了组件和页面之间的对应关系 path以及component
const routes = [
  {
    path: "/",
    component: Layout,
    // 子路由，比如 菜单管理  角色管理等
    children: [
      {
        path:"",
        component: Index,
        meta: {
          needLogin: false,
        },
      },
      {
        path: "menu",
        component: Menu,
        meta: {
          needLogin: true,
        },
      },
      {
        path: "role",
        component: Role,
        meta: {
          needLogin: true,
        },
      },
      {
        path: "user",
        component: User,
        meta: {
          needLogin: true,
        },
      },
      {
        path: "category",
        component: Category,
        meta: {
          needLogin: true,
        },
      },
      {
        path: "specs",
        component: Specs,
        meta: {
          needLogin: true,
        },
      },
      {
        path: "goods",
        component: Goods,
        meta: {
          needLogin: true,
        },
      },
    ],
  },
  {
    path: "/login",
    name: "about",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: Login,
    meta: {
      needLogin: false,
    },
  },
];

const router = new VueRouter({
  mode: "history",
  routes,
});
// 全局前置守卫
router.beforeEach((to, from, next) => {
  let info = JSON.parse(localStorage.getItem("userInfo")) || {};
  // 有的页面需要登录后查看，未登录时直接跳转到登录页
  if (to.meta.needLogin) {
    // 这些页面需要登录 此时要判断用户是否登录
    if (info.token) {
      // 有token说明登录了
      // info.menus_url 存放可以访问的url info.menus_url includes(to.path)
      next();
    } else {
      // 需要登录 但是没有登录
      next("/login");
    }
  } else {
    // 页面不需要登录就能查看
    next();
  }
});
export default router;
